package com.fruit.service.account;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.joe.utils.common.IOUtils;
import com.joe.utils.common.StringUtils;
import com.joe.utils.parse.json.JsonParser;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.Data;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 城市列表转换为json文件
 *
 * @author joe
 * @version 2018.03.08 17:23
 */
public class CityConverter {
    private static final JsonParser JSON = JsonParser.getInstance();

    public static void main(String[] args) throws IOException {
        String data = "{\"110115001\":\"兴丰街道\",\"110115002\":\"林校路街道\",\"110115003\":\"清源街道\",\"110115004\":\"亦庄地区\"," +
                "\"110115005\":\"黄村地区\",\"110115006\":\"旧宫地区\",\"110115007\":\"西红门地区\",\"110115008\":\"瀛海地区\"," +
                "\"110115009\":\"观音寺街道\",\"110115010\":\"天宫院街道\",\"110115011\":\"高米店街道\",\"110115012\":\"荣华街道\"," +
                "\"110115013\":\"博兴街道\",\"110115103\":\"青云店镇\",\"110115104\":\"采育镇\",\"110115105\":\"安定镇\"," +
                "\"110115106\":\"礼贤镇\",\"110115107\":\"榆垡镇\",\"110115108\":\"庞各庄镇\",\"110115109\":\"北臧村镇\"," +
                "\"110115110\":\"魏善庄镇\",\"110115111\":\"长子营镇\",\"110115403\":\"北京经济技术开发区\"," +
                "\"110115404\":\"中关村国家自主创新示范区大兴生物医药产业基地\",\"110115405\":\"国家新媒体产业基地\"}\n";
        System.out.println(insertScript(data));
        System.exit(0);
        Map<String, Object> json = new HashMap<>();
        json.put("RECORDS", convert(getDataFromFile("E://region.json")));
        IOUtils.saveAsFile(JSON.toJson(json), "UTF8", "E://data.json");
    }

    /**
     * 将json数据转换为插入数据库的sql
     *
     * @param data json数据
     * @return 插入数据库的sql
     */
    public static String insertScript(String data) {
        String temp = "insert into region (id,areaname,parentid,level,levelOne,levelTwo,levelThree,levelFour) values" +
                "(%s,'%s',110115,4,11,01,15,001)";
        Map<String, String> map = JSON.readAsMap(data, HashMap.class, String.class, String.class);
        StringBuilder sb = new StringBuilder();
        map.forEach((k, v) -> sb.append(String.format(temp, k, v)).append(";\n"));
        return sb.toString();
    }



    /**
     * 从文件中读取城市列表数据
     *
     * @param addr 文件路径
     * @return 文件中的城市列表数据
     * @throws IOException IO异常
     */
    public static String getDataFromFile(String addr) throws IOException {
        String data = IOUtils.read(new FileInputStream(addr), "UTF8");
        return data;
    }

    /**
     * 将城市的json数据（单层）转换为带层级的list
     * <p>
     * json数据示例：[
     * {
     * "id":110000,
     * "areaname":"北京市",
     * "parentid":0,
     * "level":"1"
     * },
     * {
     * "id":110100,
     * "areaname":"北京市",
     * "parentid":110000,
     * "level":"2"
     * }
     * ]
     *
     * @param data 城市json数据（单层）
     * @return 转换后的数据（带层级的城市列表，最外层是省列表）
     */
    public static List<City> convert(String data) {
        List<City> dataList = JSON.readAsCollection(data, ArrayList.class, City.class);
        Map<String, List<City>> cityMap = dataList.stream().collect(Collectors.groupingBy(City::getLevel));
        cityMap.get("4").stream().forEach(city -> {
            Optional<City> optional = cityMap.get("3").stream().filter(c -> c.getId().equals(city.getParentid()))
                    .findFirst();
            if (optional == null || !optional.isPresent()) {
                optional = cityMap.get("2").stream().filter(c -> c.getId().equals(city.getParentid())).findFirst();
            }
            if (optional == null || !optional.isPresent()) {
                optional = cityMap.get("1").stream().filter(c -> c.getId().equals(city.getParentid())).findFirst();
            }
            if (optional != null && optional.isPresent()) {
                List<City> cities = optional.get().getData();
                if (cities == null) {
                    cities = new ArrayList<>();
                    optional.get().setData(cities);
                }
                cities.add(city);
            }
        });

        cityMap.get("3").stream().forEach(city -> {
            Optional<City> optional = cityMap.get("2").stream().filter(c -> c.getId().equals(city.getParentid()))
                    .findFirst();
            if (optional == null || !optional.isPresent()) {
                optional = cityMap.get("1").stream().filter(c -> c.getId().equals(city.getParentid())).findFirst();
            }
            if (optional != null && optional.isPresent()) {
                List<City> cities = optional.get().getData();
                if (cities == null) {
                    cities = new ArrayList<>();
                    optional.get().setData(cities);
                }
                cities.add(city);
            }
        });

        cityMap.get("2").stream().forEach(city -> {
            Optional<City> optional = cityMap.get("1").stream().filter(c -> c.getId().equals(city.getParentid()))
                    .findFirst();
            if (optional != null && optional.isPresent()) {
                List<City> cities = optional.get().getData();
                if (cities == null) {
                    cities = new ArrayList<>();
                    optional.get().setData(cities);
                }
                cities.add(city);
            }
        });

        List<City> result = cityMap.get("1");
        return sort(result);
    }

    /**
     * 对city列表按ID升序排序
     *
     * @param data city列表
     * @return 排序后的列表
     */
    private static List<City> sort(List<City> data) {
        if (data == null || data.isEmpty()) {
            return data;
        }
        data.sort(Comparator.comparing(City::getId));
        data.parallelStream().forEach(city -> sort(city.getData()));
        return data;
    }

    @Data
    @JsonIgnoreProperties(allowSetters = true, value = "level")
    static class City {
        private String id;
        private String areaname;
        private String parentid;
        private String level;
        private List<City> data;
    }
}
